import cv2
from aip import AipFace
import json
""" 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()
"""识别人脸并提供信息"""
def dect_face(file):
    """参数：图片的绝对路径"""
    image = get_file_content(file)
    with open('LoginInfo.txt', 'r') as fp:  #打开LoginInfo.txt
        info = json.loads(fp.read())  #登录信息转换成JSON数据
    client = AipFace(info['appid'], info['apikey'], info['secretkey'])  #根据登录信息创建百度云实例
    groupId = "group1"
    identify_options = {}
    identify_face_data = client.identifyUser(groupId, image, identify_options)['result'][0]
    return identify_face_data
cascPath="./haarcascade_frontalface_alt2.xml"  #级联分类器模型
faceCascade = cv2.CascadeClassifier(cascPath)  #创建级联分类器
video_capture = cv2.VideoCapture(0)  #捕获摄像头图像流，可修改参数
while True:
   ret, frame = video_capture.read()  #获得摄像图图像
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  #将获得的图像变成灰度图
   faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=3,\
                                        minSize=(30, 30))  #识别人脸->(x, y, w, h)
   for (x, y, w, h) in faces:  #在frame中画出人脸轮廓并注明信息
      cv2.imwrite('face/example.jpg', frame)
      cv2.rectangle(frame, (x, y-20), (x+w, y+h+20), (0, 255, 0), 2)
      try:
          data = dect_face('face/example.jpg')
      except:
          pass
      #在frame上写人脸信息
      cv2.putText(frame,data['uid'],(x,y-65), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,255,255),2)
      cv2.putText(frame,data['user_info'],(x,y-30), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,255,255),2)
      break  #保证每次只处理一张人脸
   # Display the resulting frame
   cv2.imshow('Face information recognition', frame)  #显示图片，刷新很快就成了视频
   if cv2.waitKey(1) & 0xFF == ord('q'):  #英文输入法按Q退出循环
       break
video_capture.release()  # When everything is done, release the capture
cv2.destroyAllWindows()
